﻿using System.Linq;
using System.Windows;
using HappyBa.Core;
using HappyBa.Core.Data;
using HappyBa.Core.Interfaces;
using LightInject;

namespace HappyBa.Pages
{
    /// <summary>
    /// Interaction logic for ReadyToDevPage.xaml
    /// </summary>
    public partial class ReadyToDevPage 
    {
        private IDataCache dataCache;
        private Config config;
        private readonly IServiceContainer container;

        public ReadyToDevPage()
        {
            InitializeComponent();
            container = ((MainWindow)Application.Current.MainWindow).Container;
            container.GetInstance<IDataCollector>().OnDataChanged += (o, e) => OnDataContextChanged(o, new DependencyPropertyChangedEventArgs());
            DataContextChanged += OnDataContextChanged;
        }

        private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
        {
            dataCache = container.GetInstance<IDataCache>();
            config = container.GetInstance<Config>();
            if(config.Current==null)return;

            var metrics = new Metrics(dataCache.Metrics.Data, new MetricsSearch(config.Current.Search));
            var items = metrics
                .Bugs.Cast<UIEstimatableEntityBase>().OrderBy(x=>x.Priority.Name)
                .Concat(metrics.Tasks.OrderBy(x => x.Priority.Name))
                .Where(metrics.IsReadyForDevelopment)
                .ToArray();
            Info.Text = string.Format("Tasks: {0}, Bugs: {1}", 
                items.Count(metrics.IsTask),
                items.Count(metrics.IsBug)
                );
            Items.ItemsSource = items;
        }

        private void RefreshClick(object sender, RoutedEventArgs e)
        {
            OnDataContextChanged(sender,new DependencyPropertyChangedEventArgs());
        }
    }
}
